/**
 * ATuanZhang
 */
package org.huanglei.android.application;

import java.util.ArrayList;
import java.util.List;

import org.huanglei.android.inject.module.AbstractAndroidModule;
import org.huanglei.android.inject.module.AndroidModule;
import org.huanglei.android.inject.provider.InjectorProvider;

import android.app.Application;
import android.content.Context;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Provider;
import com.google.inject.Stage;

/**
 * @author huanglei
 * @date 2011-3-31 @
 */
public abstract class AndroidApplication extends Application implements
		InjectorProvider {

	protected Injector guiceInjector = null;

	protected String lock = "LOCK";

	protected Provider<Context> contextProvider = null;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.huanglei.android.inject.provider.InjectorProvider#getInjector()
	 */
	@Override
	public Injector getInjector() {
		if (guiceInjector == null) {
			synchronized (lock) {
				if (guiceInjector == null) {
					guiceInjector = createInjector();
				}
			}
		}
		return guiceInjector;
	}

	protected Injector createInjector() {
		contextProvider = new Provider<Context>() {
			public Context get() {
				return AndroidApplication.this;
			}
		};
		final ArrayList<AbstractAndroidModule> modules = new ArrayList<AbstractAndroidModule>();
		final AbstractAndroidModule module = new AndroidModule(contextProvider);
		modules.add(module);
		addApplicationModules(modules);
		return Guice.createInjector(Stage.PRODUCTION, modules);
	}

	protected abstract void addApplicationModules(
			List<AbstractAndroidModule> modules);

}
